package com.guge.sports.toolPackage.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class ExcelUtils {

    /**
     * 导出为excel
     *
     * @param list     表格数据
     * @param tClass   实体类型
     * @param response 响应
     * @param fileName 文件名  不用加后缀名
     * @param <T>      泛型
     */
    public static <T> boolean exportExcel(List<T> list, Class<T> tClass, HttpServletResponse response, String fileName) {

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), tClass).sheet().doWrite(list);
            return true;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 导入excel，需传入文件地址，和实体类的class对象
     *
     * @param uploadFile  请求文件
     * @param tClass   实体类型
     * @param <T>  泛型
     * @return  集合
     */
    public static <T> List<T> importExcel(MultipartFile uploadFile, Class<T> tClass) {
        //存放导入数据
        List<T> list = new ArrayList<>();
        //AnalysisEventListener：利用监听器获取导入数据
        try {
            EasyExcel.read(uploadFile.getInputStream(), tClass, new AnalysisEventListener<T>() {

                @Override
                public void invoke(T t, AnalysisContext analysisContext) {
                    list.add(t);
                }

                @Override
                public void doAfterAllAnalysed(AnalysisContext analysisContext) {

                }
            }).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return list;
    }

}
